package com.rimi.shiro;

import com.alibaba.fastjson.JSONObject;
import com.rimi.commons.CommonResult;
import com.rimi.commons.ResultStatus;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author luc
 * @Date 2021/7/1
 */
public class AnyRolesAuthorizationFilter extends RolesAuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        Subject subject = getSubject(request, response);
        String[] rolesArray = (String[]) mappedValue;

        if (rolesArray == null || rolesArray.length == 0) {
            //no roles specified, so nothing to check - allow access.
            return true;
        }

        for (String role : rolesArray) {
            if(subject.hasRole(role)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse resp = (HttpServletResponse)response;
        resp.setCharacterEncoding("utf-8");
        try {
            resp.getWriter().append(JSONObject.toJSONString(CommonResult.onFailed(ResultStatus.ROLE_AUTH_FAILED)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
